package com.ly.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.ly.bean.Admin;
import com.ly.mapper.AdminMapper;
import com.ly.service.AdminService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author 李岩
 * @date 2021/12/27-9:30
 * @describe
 */
@Component
@Service(interfaceClass = AdminService.class)
public class AdminServiceImpl implements AdminService {
    private final Logger logger= LoggerFactory.getLogger(AdminServiceImpl.class);
    private AdminServiceImpl(){
        System.out.println("AdminServiceImpl   的service层");
    }
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public Admin selectByPrimaryKey(Integer aId) throws Exception {
        Admin admin =null;
        try {
            logger.info("根据id查找管理员");
            admin=adminMapper.selectByPrimaryKey(aId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return admin;
    }
    //根据用户名获取admin对象
    @Override
    public Admin selectAdminByaName(String aName) throws Exception {
        logger.info("根据aName查找管理员");
        return adminMapper.selectAdminByaName(aName);
    }

    //把登录信息保存到redis中
    @Override
    public void saveLloginAdminToRedis(Admin admin) throws  Exception{
        logger.info("把登录信息保存到redis中  "+admin);
        redisTemplate.boundValueOps("adminLogin_"+admin.getAId()).set(admin);
    }

    //从redis中获取用户信息
    @Override
    public Admin findLoginAdminFromRedis(Integer aId) throws Exception{
        logger.info("从redis中获取用户信息  "+aId);
        return (Admin) redisTemplate.boundValueOps("adminLogin_" + aId).get();
    }
    //查询所有的管理员信息
    @Override
    public List<Admin> selectAllAdmin() throws Exception {
        return adminMapper.selectAllAdmin();
    }
    //删除用户角色
    @Override
    public void deleteRoleByaId(Integer aId) throws Exception {
        adminMapper.deleteRoleByaId(aId);
    }
    //从redis中删除登录的用户信息
    @Override
    public void deleteLoginAdminFromRedis(Integer aId) throws Exception {
        redisTemplate.delete("adminLogin_"+aId);
    }

    //添加用户的角色
    @Override
    public void addRolesAdmins(Integer roleId, Integer aId) throws Exception {
        adminMapper.addRolesAdmins(roleId,aId);
    }
    //更改用户的角色
    @Override
    public void updateRoleByaId(Integer aId, List<Integer> roleIds) throws Exception {
        logger.info("更改用户的角色service "+aId+";"+roleIds);
        //先删除用户的角色表
        adminMapper.deleteRoleByaId(aId);
        //然后在一条条的添加进去
        for (Integer roleId : roleIds) {
            adminMapper.addRolesAdmins(roleId,aId);
        }
        //删除redis中的用户角色的数据
        redisTemplate.delete("roles_"+aId);
    }
}
